package com.guguskins.back.common.security.utils;

import com.guguskins.back.entity.vo.ResultVo;
import com.guguskins.back.utils.JwtUtil;
import com.guguskins.back.utils.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出处理器
 * @author duttonliu
 */
@Component
public class TokenLogoutHandler implements LogoutHandler {

    private final RedisUtil redisUtil;

    public TokenLogoutHandler(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1 从header里面获取token
        //2 token不为空，移除token，从redis删除token
        String token = request.getHeader("token");
        if(token != null) {
            //从token获取用户名
            String username = JwtUtil.verifyToken(token).get("username", String.class);
            //移除
            redisUtil.delete("token_" + username);
        }
        ResponseUtil.out(response, ResultVo.success());
    }
}
